<template>
  <div>
    <label v-if="label">{{label}}</label>
    <slot></slot>
    <p v-if="error" style="color:red">{{error}}</p>
  </div>
</template>

<script>
import Schema from "async-validator";
export default {
  props: ["label", "prop"],
  inject: ["form"],
  data() {
    return {
      error: ""
    };
  },

  components: {},

  computed: {},

  mounted() {
    this.$on("validate", () => {
      console.log(this.validate());
    });
  },

  methods: {
    validate() {
      return new Promise(resolve => {
        const rules = this.form.rules[this.prop];
        const value = this.form.model[this.prop];
        let desciptor = {
          [this.prop]: rules
        };
        const schema = new Schema(desciptor);
        return schema.validate(
          {
            [this.prop]: value
          },
          error => {
            if (error) {
              this.error = error[0].message;
              resolve(false)
            } else {
              this.error = "";
              resolve(true)
            }
          }
        );
      });
    }
  }
};
</script>
<style scoped>
</style>